package com.fenghuajueli.module_user.activity.vip;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.fenghuajueli.lib_data.entity.goods.SignStatusEntity;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.listener.OnBaseClick;
import com.fenghuajueli.libbasecoreui.listener.OnListClickListener;
import com.fenghuajueli.libbasecoreui.ui.PrivacyWebActivity;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.utils.CommonUtils;
import com.fenghuajueli.libbasecoreui.utils.CustomItemDecoration;
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils;
import com.fenghuajueli.libbasecoreui.utils.PrivacyConstantsUtils;
import com.fenghuajueli.libbasecoreui.utils.QuickClickUtils;
import com.fenghuajueli.libbasecoreui.utils.RouteUtils;
import com.fenghuajueli.lib_data.constants.EventBusConstants;
import com.fenghuajueli.lib_data.entity.eventbus.EventEntity;
import com.fenghuajueli.lib_data.entity.goods.GoodsEntity;
import com.fenghuajueli.module_route.UserModuleRoute;
import com.fenghuajueli.module_user.R;
import com.fenghuajueli.module_user.activity.UserViewModelBaseActivity;
import com.fenghuajueli.module_user.adapter.VipBannerImageAdapter;
import com.fenghuajueli.module_user.adapter.VipDescAdapter;
import com.fenghuajueli.module_user.adapter.VipPriceAdapter;
import com.fenghuajueli.module_user.databinding.ActivityOpenVipBinding;
import com.fenghuajueli.module_user.dialog.SelectPayWaysDialog;
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel;
import com.fenghuajueli.module_user.model.UserViewModel;
import com.fenghuajueli.libbasecoreui.viewmodel.data.OtherCodeData;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


@Route(path = UserModuleRoute.USER_OPEN_VIP_ACTIVITY)
public class OpenVipActivity extends UserViewModelBaseActivity implements View.OnClickListener {
    private List<GoodsEntity> goodsEntityList;
    private LinearLayoutManager linearLayoutManager;
    private GoodsEntity currentGood;
    //是否是支付宝支付
    private String token = "";
    private VipPriceAdapter vipPriceAdapter;
    @Autowired(name = RouteUtils.PARAMETER_FUN_TYPE)
    int funType = 0;
    //来自于那个界面
    @Autowired(name = RouteUtils.PARAMETER_FROM)
    int parameterFrom = 0;

    private VipDescAdapter vipDescAdapter;
    private SelectPayWaysDialog selectPayWaysDialog;
    private VipBannerImageAdapter vipBannerImageAdapter;
    ActivityOpenVipBinding binding;

    /**
     * 当前选择的支付渠道方式
     */
    private String payChannel = "-1";


    private final UserViewModel userViewModel = new UserViewModel();

    @Override
    public BaseViewModel setBaseViewModel() {
        return userViewModel;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyStatusBarUtils.setStatusBarWhite(this, "#00ffffff");
        binding = ActivityOpenVipBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EventBus.getDefault().register(this);
        binding.myActionBar.setRightTextClick(new OnBaseClick<Integer>() {
            @Override
            public void onClick(Integer integer) {
                PrivacyWebActivity.start(OpenVipActivity.this, PrivacyConstantsUtils.ProtocolType.BUY_PROTOCOL);
            }
        });
        registerObserver();
        initData();
        initBanner();
        if (userViewModel != null) {
            userViewModel.handlerZfbSubscribeResult(getIntent(), this, currentGood);
        }
    }

    private void initBanner() {
        List<Integer> imgList = new ArrayList<>();
        imgList.add(R.mipmap.huiyuan_banner_bg);
        imgList.add(R.mipmap.huiyuan_banner_bg2);
        vipBannerImageAdapter = new VipBannerImageAdapter(imgList);
        binding.bannerView.setAdapter(vipBannerImageAdapter)
                .addBannerLifecycleObserver(this)
                .setLoopTime(5000);
    }

    private void initData() {
        if (UserInfoUtils.getInstance().isLogin()) {
            linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
            binding.vipRecyclerView.setLayoutManager(linearLayoutManager);
            goodsEntityList = new ArrayList<>();
            CustomItemDecoration customItemDecoration = new CustomItemDecoration(this, ConvertUtils.dp2px(4));
            binding.vipRecyclerView.addItemDecoration(customItemDecoration);
            vipPriceAdapter = new VipPriceAdapter(this, goodsEntityList);
            vipPriceAdapter.setOnItemClick(new OnListClickListener<GoodsEntity>() {
                @Override
                public void itemClick(int position, GoodsEntity data) {
                    currentGood = data;
                    binding.tvPayMoney.setText(data.getGoods_price() + "");
                }
            });
            binding.vipRecyclerView.setAdapter(vipPriceAdapter);
            token = UserInfoUtils.getInstance().getUserInfoEntity().getToken();
            //根据需求来决定是否获取订阅类商品
            userViewModel.getGoodsList(this);
        } else {
            ToastUtils.showShort("未登录");
            finish();
        }
        binding.ivBtnZfbPay.setOnClickListener(this);
        binding.ivBtnWXpay.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (QuickClickUtils.isFastClick()) {
            return;
        }
        if (currentGood == null) {
            return;
        }
        if (view.getId() == R.id.ivBtnZfbPay) {
            if (!CommonUtils.checkAliPayInstalled(this)) {
                showToast("请先安装支付宝客户端！");
                return;
            }
            payChannel = "2";
            checkUserIsSubscribeActive();
        } else if (view.getId() == R.id.ivBtnWXpay) {
            if (!CommonUtils.isWeixinAvilible(this)) {
                showToast("请先安装微信客户端！");
                return;
            }
            payChannel = "1";
            checkUserIsSubscribeActive();
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (userViewModel != null) {
            userViewModel.handlerZfbSubscribeResult(intent, this, currentGood);
        }
    }

    /**
     * 检测用户是否处于支付宝周期扣款签约中
     * 签约类商品，不管是微信下单还是支付宝下单都要先检查用户
     * 是否是订阅会员并且判断当前是否还在签约中，签约中不允许在购买其他会员
     */
    private void checkUserIsSubscribeActive() {
        if (UserInfoUtils.getInstance().isForeverVip()) {
            ToastUtils.showLong("您已是永久会员，无须再开通！");
        } else {
            if (userViewModel != null) {
                userViewModel.checkIsSubscribeZfbActive(this, currentGood, payChannel);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(EventEntity eventBusEntity) {
        if (eventBusEntity.getCode() == EventBusConstants.PAY_ERROR) {
            hideLoadingDialog();
        }
        if (eventBusEntity.getCode() == EventBusConstants.PAY_SUCCESS) {
            //延迟一秒从后台获取信息
            handlerPaySuccess();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoadingDialog();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 注册相关的数据的监听事件
     */
    private void registerObserver() {
        userViewModel.goodsList.observe(this, new Observer<List<GoodsEntity>>() {
            @Override
            public void onChanged(List<GoodsEntity> data) {
                goodsEntityList = data;
                currentGood = goodsEntityList.get(0);
                binding.tvPayMoney.setText(currentGood.getGoods_price() + "");
                if (vipPriceAdapter != null) {
                    vipPriceAdapter.refreshData(goodsEntityList);
                }
            }
        });
        userViewModel.otherStatusData.observe(this, new Observer<OtherCodeData>() {
            @Override
            public void onChanged(OtherCodeData otherCodeData) {
                switch (otherCodeData.getCode()) {
                    case OtherCodeData.PAY_SUCCESS:
                        handlerPaySuccess();
                        break;
                    case OtherCodeData.UPDATE_USER_INFO:
                        if (vipBannerImageAdapter != null) {
                            vipBannerImageAdapter.notifyDataSetChanged();
                        }
                        break;
                }
            }
        });
        //用户是否处于支付宝签约状态 需要做ui改变就设置监听
        userViewModel.signStatus.observe(this, new Observer<SignStatusEntity>() {
            @Override
            public void onChanged(SignStatusEntity signStatusEntity) {

            }
        });
    }

    private void handlerPaySuccess() {
        showLoadingDialog();
        binding.ivBtnWXpay.postDelayed(new Runnable() {
            @Override
            public void run() {
                userViewModel.updateUserInfo(OpenVipActivity.this, currentGood);
            }
        }, 1000);
    }
}